package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.service.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DateUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Service
public class StrategyStatisVORedisServiceImpl implements IStrategyStatisVORedisService{
    /*@Autowired
    private StringRedisTemplate template;
    @Autowired
    private IStrategyService strategyService;

    @Override
    public void viewnumIncrease(String sid, int num) {
        //拼接vo对象的key
        //strategy_statis_vo:sid=xxx
        String key=RedisKeys.STRATEGY_STATIS_VO.join(sid);
        //判断key是否存在
        StrategyStatisVO vo=null;
        if (!template.hasKey(key)){
            //如果不存在，初始化vo
            vo=new StrategyStatisVO();
            Strategy strategy=strategyService.get(sid);
            BeanUtils.copyProperties(strategy,vo);
        }else {
            //存在直接加num（1）
            String voStr=template.opsForValue().get(key);
            vo=JSON.parseObject(voStr,StrategyStatisVO.class);
        }
        //redis的springboot操作
        //统一加1
        vo.setViewnum(vo.getViewnum()+1);
        //更新vo
        template.opsForValue().set(key,JSON.toJSONString(vo));
    }

    @Override
    public StrategyStatisVO getStrategyStatisVo(String sid) {
        //拿到id
        String key=RedisKeys.STRATEGY_STATIS_VO.join(sid);
//判断key是否存在
        StrategyStatisVO vo=null;
        if (!template.hasKey(key)){
            //如果不存在，初始化vo
            vo=new StrategyStatisVO();
            Strategy strategy=strategyService.get(sid);
            BeanUtils.copyProperties(strategy,vo);
        }else {
            //存在直接加num（1）
            String voStr=template.opsForValue().get(key);
            vo=JSON.parseObject(voStr,StrategyStatisVO.class);
        }

        return vo;
    }*/

    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private IStrategyService strategyService;
    @Override
    public void viewnumIncrease(String sid, int num) {
        StrategyStatisVO vo = this.getStrategyStatisVo(sid);
        //viewnum + num
        vo.setViewnum(vo.getViewnum() + num);
        //更新vo对象
        this.setStrategyStatisVo(vo);
    }
    @Override
    public void replynumIncrease(String sid, int num) {
        StrategyStatisVO vo = this.getStrategyStatisVo(sid);
        //评论数+1
        vo.setReplynum(vo.getReplynum() + num);
        //更新
        this.setStrategyStatisVo(vo);
    }

    //将vo对象设置redis中
    @Override
    public void setStrategyStatisVo(StrategyStatisVO vo) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(vo.getStrategyId());
        template.opsForValue().set(key, JSON.toJSONString(vo));
    }
    @Override
    public StrategyStatisVO getStrategyStatisVo(String sid) {
        String key = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        //判断vo对象是否存在
        StrategyStatisVO vo = null;
        if(template.hasKey(key)){
            //如果存在, 然后viewnum + num
            String voStr = template.opsForValue().get(key);
            vo = JSON.parseObject(voStr, StrategyStatisVO.class);
        }else{
            //如果不存在, 先初始化, 然后viewnum + num
            vo = new StrategyStatisVO();
            Strategy strategy = strategyService.get(sid);
            //初始化,统计数据(viewnum, replynum....)
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            template.opsForValue().set(key, JSON.toJSONString(vo));
        }

        return vo;
    }

    @Override
    public boolean favor(String sid, String uid) {
        //拼接用户攻略收藏id集合的key
        String key = RedisKeys.USER_STRATEGY_FAVOR.join(uid);
        //获取redis上面用户攻略收藏id集合: sidList
        List<String> sidList = new ArrayList<>();
        if(template.hasKey(key)){
            String sidListStr = template.opsForValue().get(key);
            //解析json集合, 参数1:集合json字符串, 参数2:集合中元素类型(泛型)
            sidList = JSON.parseArray(sidListStr, String.class);
        }
        boolean flag = false;
        StrategyStatisVO vo = this.getStrategyStatisVo(sid);
        if(sidList.contains(sid)){
            //判断sid是否在sidList, 如果在表示取消收藏操作, 收藏数-1, 移除出sidList
            vo.setFavornum(vo.getFavornum() -1);
            sidList.remove(sid);
        }else{
            //判断sid是否在sidList, 如果不在表示收藏操作, 收藏数+1, 添加sidList中
            vo.setFavornum(vo.getFavornum() +1);
            sidList.add(sid);
            flag = true;
        }
        //更新list 更新vo
        template.opsForValue().set(key, JSON.toJSONString(sidList));
        this.setStrategyStatisVo(vo);
        //return flag;
        return sidList.contains(sid);
    }
    @Override
    public List<String> getUserStrategyFavor(String userId) {
        //用户没登录操作
        if (!StringUtils.hasLength(userId)) {
            return Collections.EMPTY_LIST;  //new ArrayList(); 空的集合
        }

        String key = RedisKeys.USER_STRATEGY_FAVOR.join(userId);
        List<String> sidList = new ArrayList<>();
        if(template.hasKey(key)){
            String sidListStr = template.opsForValue().get(key);
            sidList = JSON.parseArray(sidListStr, String.class);
        }
        return sidList;
    }

    @Override
    public boolean strategyThumbup(String sid, String uid) {
        //拼接记号key
        //USER_STRATEGY_FAVOR统一管理key 通过join方法将两个次数加到key中
        String signkey = RedisKeys.USER_STRATEGY_FAVOR.join(uid,sid);

        //判断key是否存在
        if (!template.hasKey(signkey)) {
            //不存在，获取vo，点赞数加1，将记号缓存到redis中，设置过期时间
            //获取vo对象
            StrategyStatisVO vo=this.getStrategyStatisVo(sid);
            //顶加1(先取redis中的顶数在设置进去)
            vo.setThumbsupnum(vo.getThumbsupnum() + 1);
            //设置到vo对象中
            this.setStrategyStatisVo(vo);
          //有效时间：今天最后一秒-当前时间
            Date now=new Date();
            Date end=DateUtil.getEndDate(now);
            long time=DateUtil.getDateBetween(now, end);
            //处理redis的记号，设置到redis中，（key，value：1，时间，时间单位
            template.opsForValue().set(signkey, "1", time, TimeUnit.SECONDS);
        }

        //存在不做操作
        return false;
    }

    //判断指定vokey是否存在redis中
    @Override
    public boolean isStrategyVoExists(String id) {
        //判断vo对象的key是否存在
        //攻略统计vo的key实例对象 STRATEGY_STATIS_VO
        String key = RedisKeys.STRATEGY_STATIS_VO.join(id);
        return template.hasKey(key);
    }

    @Override
    public List<StrategyStatisVO> queryStrategyVoByPattern(String pattern) {

        List<StrategyStatisVO> list = new ArrayList<>();
        //strategy_statis_vo:*查询这个作为前缀的数据
        String keyPattern =  RedisKeys.STRATEGY_STATIS_VO.join(pattern);

        //vo的key的集合
        Set<String> keys = template.keys(keyPattern);

        if(keys != null && keys.size() > 0){
            //遍历vo的key集合, 获取vo对象
            for (String key : keys) {
                String voStr = template.opsForValue().get(key);
                //塞进去
                list.add(JSON.parseObject(voStr, StrategyStatisVO.class));
            }
        }
        return list;
    }

    @Override
    public void visitorNum(String oId, int num) {
        StrategyStatisVO vo = this.getStrategyStatisVo(oId);
        //viewnum + num
        vo.setViewnum(vo.getTotalView() + num);
        //更新vo对象
        this.setStrategyStatisVo(vo);
    }

}
